using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using Core;
using System.Reflection;
using SPHelpCollectionBuilder.Icons;
using System.IO;

namespace SPHelpCollectionBuilder
{
    public partial class MainForm : Form
    {
        public static ProjectTree projectTree = null;

        public MainForm()
        {
            InitializeComponent();

            panelSave.Visible = false;
                 
            projectTree = new ProjectTree();
            projectTree.Width = splitContainer1.Panel1.Width;
            projectTree.Height = splitContainer1.Panel1.Height;
            projectTree.Anchor = AnchorStyles.Left | AnchorStyles.Top | AnchorStyles.Bottom | AnchorStyles.Right;
            splitContainer1.Panel1.Controls.Clear();
            splitContainer1.Panel1.Controls.Add(projectTree);
            projectTree.OnManifestNodeSelect = new EventHandler(HandleManifestNodeSelect);
            projectTree.OnHelpCategoryNodeSelect = new EventHandler(HandleHelpCategoryNodeSelect);
            projectTree.OnHelpContextNodeSelect = new EventHandler(HandleHelpContextNodeSelect);
            projectTree.OnHelpCssNodeSelect = new EventHandler(HandleHelpCssNodeSelect);
            projectTree.OnHelpImageNodeSelect = new EventHandler(HandleHelpImageNodeSelect);
            projectTree.OnHelpScriptNodeSelect = new EventHandler(HandleHelpScriptNodeSelect);
            projectTree.OnHelpTopicNodeSelect = new EventHandler(HandleHelpTopicNodeSelect);

            Utils.UpdateWarningHandler = new UpdateWarningDelegate(UpdateWarningPanel);

            Assembly assem = Assembly.GetExecutingAssembly();
            pictureBoxProjectIcon.Image = Image.FromStream(assem.GetManifestResourceStream(typeof(Dummy), "hammer.png"));
            pictureBoxHelpCategoryIcon.Image = Image.FromStream(assem.GetManifestResourceStream(typeof(Dummy), "helpCategory.png"));
            pictureBoxHelpContextIcon.Image = Image.FromStream(assem.GetManifestResourceStream(typeof(Dummy), "helpContext.png"));
            pictureBoxHelpCssIcon.Image = Image.FromStream(assem.GetManifestResourceStream(typeof(Dummy), "helpCss.png"));
            pictureBoxHelpImageIcon.Image = Image.FromStream(assem.GetManifestResourceStream(typeof(Dummy), "helpImage.png"));
            pictureBoxHelpScriptIcon.Image = Image.FromStream(assem.GetManifestResourceStream(typeof(Dummy), "helpScript.png"));
            pictureBoxHelpTopicIcon.Image = Image.FromStream(assem.GetManifestResourceStream(typeof(Dummy), "helpTopic.png"));
        }

        /// <summary>
        /// Exit event
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void exitToolStripMenuItem_Click(object sender, EventArgs e)
        {
            KillApplication();
        }

        /// <summary>
        /// Update messages
        /// </summary>
        /// <param name="message"></param>
        private void UpdateWarningPanel(string message)
        {
            textBoxWarning.Text = string.Concat(textBoxWarning.Text, Environment.NewLine, message);
            textBoxWarning.SelectionStart = textBoxWarning.TextLength;
            textBoxWarning.ScrollToCaret();
            textBoxWarning.Focus();
            this.Update();
        }

        /// <summary>
        /// Exit
        /// </summary>
        private void KillApplication()
        {
            Application.Exit();
        }

        /// <summary>
        /// Create a new HC
        /// </summary>
        private void NewHelpCollection()
        {
            using (NewProjectForm newForm = new NewProjectForm())
            {
                DialogResult dResult = newForm.ShowDialog(this);
                if (dResult == DialogResult.OK)
                {
                    string folderPath = newForm.FolderPath;
                    string projectName = newForm.ProjectName;
                    HCProject project = HCProjectManager.CreateProject(folderPath, projectName, newForm.ManifestId);
                    projectTree.LoadProjectTree();
                }
            }
        }

        /// <summary>
        /// Open an existing project
        /// </summary>
        private void OpenProject()
        {
            try
            {
                DialogResult dResult = folderBrowserDialog1.ShowDialog(this);
                if (dResult == DialogResult.OK)
                {
                    List<string> warningMessage = new List<string>();
                    HCProject project = HCProjectManager.LoadProject(folderBrowserDialog1.SelectedPath, ref warningMessage);

                    foreach (string str in warningMessage)
                    {
                        UpdateWarningPanel(str);
                    }
                    
                    projectTree.LoadProjectTree();
                }
            }
            catch (Exception ex)
            {
                HandleException(ex);
            }
        }

        /// <summary>
        /// Open event handler
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void openHelpCollectionToolStripMenuItem_Click(object sender, EventArgs e)
        {
            OpenProject();
        }

        /// <summary>
        /// Display error
        /// </summary>
        /// <param name="e"></param>
        void HandleException(Exception e)
        {
            MessageBox.Show(e.Message, "Error", MessageBoxButtons.OK);
        }

        /// <summary>
        /// Manifest selected
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void HandleManifestNodeSelect(object sender, EventArgs e)
        {
            HCManifest man = (HCManifest)sender;
            ManifestEditor editor = new ManifestEditor();
            panelMain.Controls.Clear();
            panelMain.Controls.Add(editor);
            editor.Width = panelMain.Width;
            editor.Height = panelMain.Height;
            editor.Anchor = AnchorStyles.Left | AnchorStyles.Top | AnchorStyles.Bottom | AnchorStyles.Right;
            editor.Manifest = man;
            editor.LoadManifest();
        }

        private void HandleHelpContextNodeSelect(object sender, EventArgs e)
        {
            HelpContext con = (HelpContext)sender;

            HelpContextEditor editor = new HelpContextEditor();
            panelMain.Controls.Clear();
            panelMain.Controls.Add(editor);

            editor.Width = panelMain.Width;
            editor.Height = panelMain.Height;
            editor.Anchor = AnchorStyles.Left | AnchorStyles.Top | AnchorStyles.Bottom | AnchorStyles.Right;
            editor.CurrentHelpContext = con;
            editor.LoadHelpContext();
        }

        private void HandleHelpCssNodeSelect(object sender, EventArgs e)
        {
            HelpCss css = (HelpCss)sender;

            HelpCssEditor editor = new HelpCssEditor();
            panelMain.Controls.Clear();
            panelMain.Controls.Add(editor);

            editor.Width = panelMain.Width;
            editor.Height = panelMain.Height;
            editor.Anchor = AnchorStyles.Left | AnchorStyles.Top | AnchorStyles.Bottom | AnchorStyles.Right;
            editor.CurrentHelpCss = css;
            editor.LoadHelpCss();
        }

        private void HandleHelpImageNodeSelect(object sender, EventArgs e)
        {
            HelpImage img = (HelpImage)sender;

            HelpImageEditor editor = new HelpImageEditor();
            panelMain.Controls.Clear();
            panelMain.Controls.Add(editor);

            editor.Width = panelMain.Width;
            editor.Height = panelMain.Height;
            editor.Anchor = AnchorStyles.Left | AnchorStyles.Top | AnchorStyles.Bottom | AnchorStyles.Right;
            editor.CurrentHelpImage = img;
            editor.LoadHelpImage();
        }

        private void HandleHelpScriptNodeSelect(object sender, EventArgs e)
        {
            HelpScript script = (HelpScript)sender;
            HelpScriptEditor editor = new HelpScriptEditor();
            panelMain.Controls.Clear();
            panelMain.Controls.Add(editor);

            editor.Width = panelMain.Width;
            editor.Height = panelMain.Height;
            editor.Anchor = AnchorStyles.Left | AnchorStyles.Top | AnchorStyles.Bottom | AnchorStyles.Right;
            editor.CurrentHelpScript = script;
            editor.LoadHelpScript();
        }

        private void HandleHelpTopicNodeSelect(object sender, EventArgs e)
        {
            HelpTopic topic = (HelpTopic)sender;
            HelpTopicEditor editor = new HelpTopicEditor();
            panelMain.Controls.Clear();
            panelMain.Controls.Add(editor);

            editor.Width = panelMain.Width;
            editor.Height = panelMain.Height;
            editor.Anchor = AnchorStyles.Left | AnchorStyles.Top | AnchorStyles.Bottom | AnchorStyles.Right;
            editor.CurrentHelpTopic = topic;
            editor.LoadHelpTopic();
        }
        
        /// <summary>
        /// Category selected
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void HandleHelpCategoryNodeSelect(object sender, EventArgs e)
        {
            HelpCategory cat = (HelpCategory)sender;

            HelpCategoryEditor editor = new HelpCategoryEditor();
            panelMain.Controls.Clear();
            panelMain.Controls.Add(editor);

            editor.Width = panelMain.Width;
            editor.Height = panelMain.Height;
            editor.Anchor = AnchorStyles.Left | AnchorStyles.Top | AnchorStyles.Bottom | AnchorStyles.Right;
            editor.CurrentHelpCategory = cat;
            editor.LoadHelpCategory();
        }

        /// <summary>
        /// Create new help collection
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void newHelpCollectionToolStripMenuItem_Click(object sender, EventArgs e)
        {
            NewHelpCollection();
        }

        private void SaveControls()
        {
            foreach (Control ctrl in panelMain.Controls)
            {
                if (ctrl is ISavableControl)
                {
                    ISavableControl c = (ISavableControl)ctrl;
                    c.SaveData();
                }
            }
        }

        /// <summary>
        /// Hide/show save panel
        /// </summary>
        private void EnableDisableSaveButton()
        {
            foreach (Control ctrl in panelMain.Controls)
            {
                if (ctrl is ISavableControl)
                {
                    panelSave.Enabled = true;
                    panelSave.Visible = true;
                    this.Update();
                    return;
                }
            }

            panelSave.Visible = false;
            panelSave.Enabled = false;
            this.Update();
        }

        private void SaveAll()
        {
            SaveControls();
            HCProjectManager.CurrentProject.SaveProjectToDisk();
            Utils.UpdateWarningHandler("Done saving project");

            projectTree.LoadProjectTree();
            Utils.UpdateWarningHandler("Done loading project after savings");

            Global.HAS_CHANGES_IN_MEMORY_NOT_SAVED_TO_DISK = false;
        }

        private void btnSave_Click_1(object sender, EventArgs e)
        {
            SaveAll();
        }

        private void panelMain_ControlAdded_1(object sender, ControlEventArgs e)
        {
            EnableDisableSaveButton();
        }

        private void panelMain_ControlRemoved_1(object sender, ControlEventArgs e)
        {
            EnableDisableSaveButton();
        }

        private void makeCabToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            if (HCProjectManager.CurrentProject == null)
            {
                MessageBox.Show("No project", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            string cabOutput = string.Empty;

            string cabFilePath = HCProjectManager.MakeCab(ref cabOutput);
            MessageBox.Show(string.Concat("A cab file has been made: ", cabFilePath), string.Empty, MessageBoxButtons.OK, MessageBoxIcon.Information);
            Utils.UpdateWarningHandler(cabOutput);
            
            Utils.OpenFileInExplorer(Path.GetDirectoryName(cabFilePath));
        }

        private void installHelpCollectionToolStripMenuItem_Click(object sender, EventArgs e)
        {
            DialogResult dResult = MessageBox.Show("To install help collection on this machine, this machine must be a SharePoint web front end server, continue?", "Information", MessageBoxButtons.YesNo, MessageBoxIcon.Information);

            if (dResult == DialogResult.Yes)
                projectTree.InstallHC();
        }

        private void uninstallHelpCollectionOnThisMachineToolStripMenuItem_Click(object sender, EventArgs e)
        {
            projectTree.UninstallHC();
        }

        private void MainForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (Global.HAS_CHANGES_IN_MEMORY_NOT_SAVED_TO_DISK)
            {
                DialogResult dResult = MessageBox.Show("There are unsaved changes, save now?", "Warning", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);
                if (dResult == DialogResult.Yes)
                {
                    HCProjectManager.CurrentProject.SaveProjectToDisk();
                    Global.HAS_CHANGES_IN_MEMORY_NOT_SAVED_TO_DISK = false;
                }
            }
        }

        private void helpToolStripMenuItem_Click(object sender, EventArgs e)
        {
            using (About a = new About())
            {
                a.StartPosition = FormStartPosition.CenterParent;
                //a.Parent = this;
                a.ShowDialog();
            }
        }
    }
}